﻿using System;
using System.IO;
using RayDen.Library.Core;
using RayDen.Library.Core.Primitives;
using RayDen.Library.Data;
using RayDen.Library.Data.Imaging;
using RayDen.RayEngine;
using RayDen.RayEngine.Core.Types;
using RayDen.RayEngine.Corrector.Managers;
using RayEngine.Spectral.Entities.Materials;

namespace RayEngine.Spectral.Entities.Lighting
{
    public class BasicInfiniteLight : BaseInfiniteLight
    {
        public IEnvironmentMapSampler Sampler;


        public BasicInfiniteLight(RgbSpectrumTexture tx, RgbSpectrumTexture tx_l, LightMaterial mt) : base(mt)
        {
            Sampler = new LatLongMap(tx, tx_l);
        }

        public BasicInfiniteLight(IEnvironmentMapSampler envMap, LightMaterial mt) : base(mt)
        {
            Sampler = envMap;
        }

        public override void EvaluateIllumination(RayEngineScene scn, float u0, float u1, float u2, float u3, float u4, out RayData ray,
            out float pdf, out IColorType radiance)
        {
            throw new System.NotImplementedException();
        }

        public override IColorType Le(ref Vector dir)
        {
            RgbSpectrumInfo sm;
            if (dir.y > -MathLab.Epsilon && dir.y <= MathLab.Epsilon)
            {
                dir.y += 0.005f;
            }

            Sampler.Sample(ref dir, out sm);
            //sm.Mul(gain.c1);

            return ColorManager.Instance.Convert(sm, SpectrumType.Illuminant);
        }

        private static RgbSpectrumTexture Load(string fn)
        {
            if (string.IsNullOrWhiteSpace(fn))
                return null;
            if (Path.GetExtension(fn).NameContains("hdr", "exr"))
                return ImageFactory.FreeImageLoadExrBitmap(fn);
            return ImageFactory.FreeImageLoadBitmap(fn);
        }

        private static string GetTlFilename(string fileName)
        {
            var ext = Path.GetExtension(fileName);

            var fn = Path.GetFileNameWithoutExtension(fileName);
            var variants = new[]
                {
                    string.Format("{0}_env{1}", fn, ext),
                    string.Format("{0}_gi{1}", fn, ext),
                    string.Format("{0}_env{1}", fn.Substring(0, Math.Max(0,fn.Length-4)), ext),
                    string.Format("{0}_env{1}", fn.Substring(0, Math.Max(0,fn.Length-5)), ext),
                };
            foreach (var ltFile in variants)
            {
                var f = string.Format("{0}\\{1}", Path.GetDirectoryName(fileName), ltFile);
                if (File.Exists(f))
                    return f;
            }

            return string.Empty;
        }
    }
}